package com.mailsending.service;

import com.mailsending.entity.EmailEntity;
import com.mailsending.mapper.SendingMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;

/**
 * 邮件业务类 MailService
 */
@Service
public class MailService {
    private Logger logger = LoggerFactory.getLogger(getClass());//提供日志类

    @Autowired
    private JavaMailSenderImpl mailSender;//注入邮件工具类

    @Autowired
    private SendingMapper sendingMapper;

    /**
     * 发送邮件
     */
    public EmailEntity sendMail(EmailEntity entity) {
        try {
            checkMail(entity); //1.检测邮件
            sendMimeMail(entity); //2.发送邮件
            return saveMail(entity); //3.保存邮件
        } catch (Exception e) {
            logger.error("发送邮件失败:", e);//打印错误信息
            entity.setStatus("fail");
            entity.setError(e.getMessage());
            return entity;
        }

    }

    //1、检测邮件信息类
    private void checkMail(EmailEntity entity) {
        if (StringUtils.isEmpty(entity.getReceiver())) {
            throw new RuntimeException("邮件收信人不能为空");
        }
        if (StringUtils.isEmpty(entity.getTheme())) {
            throw new RuntimeException("邮件主题不能为空");
        }
        if (StringUtils.isEmpty(entity.getMailContent())) {
            throw new RuntimeException("邮件内容不能为空");
        }
    }

    //2、构建复杂邮件信息类
    private void sendMimeMail(EmailEntity entity) {
        try {
            //true表示支持复杂类型
            MimeMessageHelper messageHelper = new MimeMessageHelper(mailSender.createMimeMessage(), true);
            //邮件发信人从配置项读取
            entity.setSender(getMailSendFrom());
            //邮件发信人
            messageHelper.setFrom(entity.getSender());
            //邮件收信人
            messageHelper.setTo(entity.getReceiver().split(","));
            //邮件主题
            messageHelper.setSubject(entity.getTheme());
            //邮件内容
            messageHelper.setText(entity.getMailContent());
            if (!StringUtils.isEmpty(entity.getCc())) {
                //抄送
                messageHelper.setCc(entity.getCc().split(","));
            }
            if (!StringUtils.isEmpty(entity.getBcc())) {
                //密送
                messageHelper.setCc(entity.getBcc().split(","));
            }
            if (entity.getMultipartFiles() != null) {
                //添加邮件附件
                for (MultipartFile multipartFile : entity.getMultipartFiles()) {
                    messageHelper.addAttachment(multipartFile.getOriginalFilename(), multipartFile);
                }
            }
            if (StringUtils.isEmpty(entity.getSentDate())) {
                //发送时间
                entity.setSentDate(new Date());
                messageHelper.setSentDate(entity.getSentDate());
            }
            //正式发送邮件
            mailSender.send(messageHelper.getMimeMessage());
            entity.setStatus("ok");
            logger.info("发送邮件成功：{}->{}", entity.getSender(), entity.getReceiver());
        } catch (Exception e) {
            //发送失败
            throw new RuntimeException(e);
        }
    }

    //3、保存邮件
    private EmailEntity saveMail(EmailEntity entity) {
        //将邮件保存到数据库
        System.out.println(entity);
        sendingMapper.emailSendingAdd(entity);
        return entity;
    }

    //获取邮件发信人
    public String getMailSendFrom() {
        return mailSender.getJavaMailProperties().getProperty("sender");
    }

}
